/******************************************************************
 * Created by: DO HOANG HAI                                       
 * Date of Creation: 15/Aug/2007
 * Date of last modification: 22/2/2008
 *                                                                
 * Description: starting point of the applicatioin
 ******************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace Pbdms
{
    static class Program
    {
        //listening thread
        public static Thread thTcpListener;
        public static BusinessLogic.Network.NetworkController networkCtrller;
        public static NotifyIcon notifyIcon1;
        public static Pbdms.Forms.FrmMain mainForm;
        public static Pbdms.Views.FrmProgress formProgess;
        private static bool isForcedToExit = false;
        
       
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);



            if (isDuplicatedProgramRunning() == false)
            {
                 setting();
                 //check XML database files
                 formProgess = new Pbdms.Views.FrmProgress();
                 System.Threading.Thread mThread = new System.Threading.Thread(PreInit_App);
                 formProgess.Show_Progress(ref mThread, "Pbdms - Starting up, please wait.");
                 
                 if (isForcedToExit)
                 {                     
                     //if there is any file missing, stop the program
                     return;
                 }
                 //otherwise
                 notifyIcon1 = new NotifyIcon();
                 notifyIcon1.Icon = Pbdms.Properties.Resources.pbdms_big;
                 notifyIcon1.DoubleClick += new EventHandler(notifyIcon1_DoubleClick);
                 try
                 {
                     //open the network
                     includeListenerThread();
                     //start the main form
                     mainForm = new Pbdms.Forms.FrmMain();
                     mainForm.ShowDialog();
                 }
                 catch
                 {
                     Common.Global.showMsgOneButton("An unexpected error has occurred !\r\nPress enter to close the program", 'C');
                 }
                 Application.Run();
             }            
             else {                 
                 closeNetwork();
                 Application.Exit();                
             }
         }

         /// <summary>
         /// check the library for any database files missing or other 
         /// document files missing in the library. if so, display the list to 
         /// </summary>
         private static void PreInit_App()
         {
             //force the program to pause for extra 2 seconds
             System.Threading.Thread.CurrentThread.Join(2000);

             ArrayList arl = new ArrayList();
             if (hasXMLFilesMissing(ref arl) == true)
             {
                 object[] arr = arl.ToArray();
                 System.Text.StringBuilder sb = new System.Text.StringBuilder();
                 sb.Append("Following files are not in the library:");
                 for (int j = 0; j < arr.Length; j++)
                 {
                     if (j==0)
                         sb.Append(arr[j].ToString());
                     else
                         sb.Append(", " + arr[j].ToString());
                 }
                 sb.Append("\r\nPlease check and correct the library before start up the program");
                 Common.Global.showMsgOneButton(sb.ToString(), 'W');
                 isForcedToExit = true;
                 
             }
         }
        
        /// <summary>
        /// check for any XML Database files missing
        /// </summary>
        /// <param name="arl"></param>
        /// <returns></returns>
        private static bool hasXMLFilesMissing(ref ArrayList arl)
        {
            bool result = false;
            AppSetting aSetting = new AppSetting();

            if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\Data\\item.xml"))
            {
                result = true;
                arl.Add("item.xml");
            }
            if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\Data\\buddy.xml"))
            {
                result = true;
                arl.Add("buddy.xml");
            }
            if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\Data\\fileInfo.xml"))
            {
                result = true;
                arl.Add("fileInfo.xml");
            }
            if (!System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\Data\\comment.xml"))
            {
                result = true;
                arl.Add("comment.xml");
            }
            return result;
        }

        /// <summary>
        /// when user double clicks on the icon on system tray, resume the program's main form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            mainForm.Show();
            mainForm.WindowState = FormWindowState.Normal;
            mainForm.ShowInTaskbar = true;
            Program.notifyIcon1.Visible = false;
        }
        /// <summary>
        /// close the network
        /// </summary>
        public static void closeNetwork()
        {
            if (networkCtrller != null)
            {
                networkCtrller.stopListening();
                if (thTcpListener != null)
                {
                    thTcpListener.Abort();
                    thTcpListener = null;
                }
            }
        }
        /// <summary>
        /// check to see if an instance of the program is already running
        /// </summary>
        /// <returns></returns>
        private static bool isDuplicatedProgramRunning()
         {            
             try {               
                 System.Diagnostics.Process cp = System.Diagnostics.Process.GetCurrentProcess();
                 foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) {                    
                     if (cp.Id != p.Id & cp.ProcessName == p.ProcessName) {                        
                         Common.Global.showMsgOneButton("Programm is allready running!\r\nCurrently running: " + p.Id 
                             + " " + p.ProcessName + "\r\nThis Process " + cp.Id + " " + cp.ProcessName 
                             + "\r\nProgramm is shuting down!",'I');                        
                         return true;                        
                     }                    
                 }                
                 return false;
             }            
             catch 
             {
                 return false;
             }      
        }
        /// <summary>
        /// set the setting for the applicatoin (for the first time only)
        /// </summary>
        private static void setting()
        {
            AppSetting aSetting = new AppSetting();
            if (aSetting.LibFolder.Equals(""))
            {
                aSetting.LibFolder = System.Windows.Forms.Application.StartupPath + "\\Library";
                aSetting.Save();
            }
        }
        /// <summary>
        /// start listening on the network
        /// </summary>
        private static void includeListenerThread()
        {
            ThreadStart thsListenerThread = new ThreadStart(listenerThreadMethod);

            thTcpListener = new Thread(thsListenerThread);
            thTcpListener.Name = "Listener";
            thTcpListener.Start();

        }
        /// <summary>
        /// method to listen on the network
        /// </summary>
        private static void listenerThreadMethod()
        {
            networkCtrller = new BusinessLogic.Network.NetworkController();
            //add event handler for network controller object

            //network controller start to take place
            networkCtrller.startListening();

        }
        /// <summary>
        /// close the program
        /// </summary>
        public static void exit()
        {            
            if (networkCtrller!=null)
                closeNetwork();
            Application.Exit();
        }
    }
}